/**
 * unimp 类
 */
const mp = uni.requireNativePlugin('uniMP');
export default class uniMp {

	// 监听小程序通讯数据
	static receiveEvent() {
		mp.onUniMPEventReceive(ret => {
			console.log('Receive event frome MP: ' + JSON.stringify(ret));
		});
	}

	// 初始化小程序
	static initMP(parameter) {
		mp.getUniMPVersion(parameter.appid, (ret) => {
			// this.downLoadWgt(parameter)
			if (0 != ret.code) { //获取失败时安装应用
				// console.log('先安装小程序#####################');
				this.doInstallMP(parameter);
			} else {
				console.log(ret, '版本信息============');
				this.openMp(parameter);
			}
		});
	}

	/**
	 * appid  小程序id
	 * path 打开指定页面
	 * extraData:{name:'',id:''}  携带得参数
	 */
	static openMp(parameter) {
		mp.openUniMP(parameter, (ret) => {
			if (0 != ret.code) {
				uni.showModal({
					title: '启动失败',
					content: JSON.stringify(ret),
					showCancel: false
				});
			}
		});
	}

	// 安装小程序
	static doInstallMP(parameter) {
		mp.installUniMP({
			appid: parameter.appid,
			wgtFile: '/static/wgt/' + parameter.appid + '.wgt'
		}, (r) => {
			if (0 == r.code) {
				// console.log('安装成功');
				this.openMp(parameter)
			} else {
				// 没有找到安装包，需要下载后在安装 
				if (r.code === -1004 && parameter.url) {
					this.downLoadWgt(parameter)
				} else {
					uni.showModal({
						title: '安装失败',
						content: JSON.stringify(r),
						showCancel: false
					});
				}
			}
		});
	}

	// 下载wgt包,并安装
	static downLoadWgt(parameter) {
		uni.downloadFile({
			url: parameter.url,
			success: (downloadResult) => {
				console.log(downloadResult.tempFilePath)
				if (downloadResult.statusCode === 200) {
					mp.installUniMP({
						appid: parameter.appid,
						wgtFile: downloadResult.tempFilePath
					}, (r) => {
						if (0 == r.code) {
							// console.log('安装成功，并去打开');
							this.openMp(parameter)
						} else {
							uni.showModal({
								title: '安装失败',
								content: JSON.stringify(r),
								showCancel: false
							});
						}
					});
				}
			}
		});
	}

	// 设置菜单
	/**
	 * @param {Object} items [{
	 *	title: "关于",
	 *	id: "about"
	 * }, {
	 * title: "分享",
	 *	id: "share"
	 *	}]	 
	 */
	menuItems(itemArr) {
		mp.setDefaultMenuItems({
			items: itemArr
		}, ret => {
			if (ret.id == "about") {
				console.log("点击了 关于")
			}
		})
	}

	sendEvent() {
		uni.showModal({
			title: '开始发送消息====',
			content: '111111111111'
		})
		mp.sendUniMPEvent(
			'__UNI__130310D',
			'event', {
				'key': 'value',
				'name': 'data'
			},
			(ret) => {
				uni.showModal({
					title: '发送消息成功',
					content: 'Host sendEvent: ' + JSON.stringify(ret)
				})
				console.log('Host sendEvent: ' + JSON.stringify(ret));
			});
	}

	sendEventInterval() {
		setInterval(this.sendEvent, 5000);
	}
}